package dq.study.designmodel.filter;

import java.util.ArrayList;
import java.util.List;

/**
 * 过滤器链
 *
 * @author dongqun
 * @modify 2021/05/08 16:15:00
 *
 * <p>
 * 减少filter中不必要的chain传递
 * </p>
 * @since 2019/3/9 16:06
 */
public class FilterChain implements Filter {

    List<Filter> filters = new ArrayList<>();
    int index;

    public FilterChain addFilter(Filter filter) {
        filters.add(filter);
        return this;
    }

    @Override
    public int filter(Request request, Response response, FilterChain chain) {
        doFilter(request,response);
        return 0;
    }

    public void doFilter(Request request, Response response) {
        if (index == filters.size()) return;
        index++;
        int state = filters.get(index - 1).filter(request, response, this);
    }
}
